package me.shep.wishlist.client;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.shep.wishlist.client.RPC.InventoryService;
import me.shep.wishlist.client.RPC.InventoryServiceAsync;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DecoratedTabPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.TreeListener;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class WishList implements EntryPoint {

	List<Person> people;
	Tree inventoryTree;
	String token;
	Label logout = new Label();
	Person user;
	Label userLabel = new Label();
	//Button logout = new Button();
	DecoratedTabPanel tabPanel = new DecoratedTabPanel();
	  /**
	   * The wrapper around the content.
	   */
	  private SimplePanel contentWrapper = new SimplePanel();
	  /**
	   * A mapping of inventory items to the widget display when the item is selected.
	   */
	  private HashMap<Object, Widget> inventoryWidgets = new HashMap<Object, Widget>();

	  public void createInventoryTree() {
		inventoryTree = new Tree();
		inventoryTree.setAnimationEnabled(true);
		InventoryServiceAsync.impl.getPeople(token, getPeopleCallback);
		
		inventoryTree.addTreeListener(new TreeListener() {
		      public void onTreeItemSelected(TreeItem item) {
		    	  //contentWrapper.setWidget(itemWidgets.get(item));
		    	  //item.setState(true);  //open the tree item when clicked, (can't collapse doing it this way...)
		      }

			public void onTreeItemStateChanged(TreeItem item) {				
			}
		});
		//inventoryTree.addStyleName(DEFAULT_STYLE_NAME + "-menu");
	  }
	  
		public void buildTree() {
			for (Person p : people) {
				TreeItem tempb = inventoryTree.addItem(p.getName());
				//itemWidgets.put(tempb, new BrandWidget(b));
				for (DesiredItem di : p.getDesiredItems()) {
					TreeItem tempc = tempb.addItem(di.getName());
					//itemWidgets.put(tempc, new CampaignWidget(ca));
				
					//itemWidgets.put(tempc.addItem("Add New Creative..."), new AddCreativeWidget(ca));				
				}
				//itemWidgets.put(tempb.addItem("Add New Campaign..."), new AddCampaignWidget(b));			
			}
			//TreeItem tempb = inventoryTree.addItem("Add New Brand...");
			//itemWidgets.put(tempb, new AddBrandWidget());
		}
		
		public void buildTabs() {
			//TODO:  This is bad, we assume user is set, but if it isn't then we will error out...  Command queue?
			//Inefficient, but, meh
			for (Person p : people) {
				if(p.getId() == user.getId())
					tabPanel.add(new ListItemsWidget(p, user), "You");
			}
			for (Person p : people) {
				if(p.getId() != user.getId())
					tabPanel.add(new ListItemsWidget(p, user), p.getName());
			}
			tabPanel.selectTab(0);
			//TreeItem tempb = inventoryTree.addItem("Add New Brand...");
			//itemWidgets.put(tempb, new AddBrandWidget());
		}
  /**
   * This is the entry point method.
   */
  public void onModuleLoad() {/*
//	  get the browser's current URL param string (if there is any)
	  String paramstr = getParamString();

//	  display the param string to the hosted shell
	  GWT.log(paramstr, null);

//	  parse the URL param string to a HashMap
	  HashMap<String, String> params = parseParamString(paramstr);
	  
//	  print out the parsed HashMap
	  if (params != null && params.containsKey("token"))
		  GWT.log(params.get("token"), null);
	  else {
		  Window.alert("You must login!");*/
	  String t = Window.Location.getParameter("token");
	  if(t != null) {
		  Date now = new Date();
		  long nowLong = now.getTime();
		  nowLong = nowLong + (1000 * 60 * 60);//1 hour
		  now.setTime(nowLong);
	  
		  Cookies.setCookie("token", t, now);
		  InventoryServiceAsync.impl.login(t, loginCallback);
		  token = t;
	  }
	  else if (Cookies.getCookie("token") != null) {
		  Date now = new Date();
		  long nowLong = now.getTime();
		  nowLong = nowLong + (1000 * 60 * 60);//1 hour
		  now.setTime(nowLong);
		  token = Cookies.getCookie("token");
		  Cookies.setCookie("token", token, now);  //refresh expiry 
		  InventoryServiceAsync.impl.login(Cookies.getCookie("token"), loginCallback);
		  
	  }
	  else {
		  Window.alert("You must login!");
		  
		  Window.Location.assign(Window.Location.getHref().substring(0,Window.Location.getHref().lastIndexOf("/")+1));  //uncomment for real deployment
		 // Window.alert(Window.Location.getHref().substring(0,Window.Location.getHref().lastIndexOf("/")+1));
		  return;
	  }
	  logout.setText("Logout");
	  logout.addClickListener(new ClickListener(){
		   public void onClick(Widget sender) {
			   InventoryServiceAsync.impl.logout(token, logoutCallback);
		  }      
		});

	  tabPanel.setAnimationEnabled(true);
	  logout.setStyleName("wl-LogoutButton");
	  VerticalPanel vp = new VerticalPanel();
	  HorizontalPanel hp = new HorizontalPanel();
	  
	  hp.add(userLabel);
	  hp.add(logout);
	  //vp.add(logout);
	  vp.add(hp);
	  vp.add(tabPanel);
	  hp.setWidth("100%");
	  hp.setCellHorizontalAlignment(logout, HasHorizontalAlignment.ALIGN_RIGHT);
	  hp.setCellHorizontalAlignment(userLabel, HasHorizontalAlignment.ALIGN_LEFT);
	  
	  vp.setSpacing(15);


	  RootPanel.get().add(vp);
	  /*
	  createInventoryTree();
	  HorizontalPanel hp = new HorizontalPanel();
	  hp.add(inventoryTree);
	  hp.add(contentWrapper);
	  RootPanel.get().add(hp);*/
	 // Window.alert("Logged in!  Cookie: " + Cookies.getCookie("token"));
	  //InventoryServiceAsync.impl.getPeople(getPeopleCallback);
	  //InventoryServiceAsync.impl.login("asklflakhsdlfhi2h938rhf98", loginCallback);
	  //InventoryServiceAsync.impl.logout("asklflakhsdlfhi2h938rhf98", logoutCallback);
	  //RootPanel.get().add(new Label("temp"));
  }

	AsyncCallback<Person> loginCallback = new AsyncCallback<Person>() {
		  public void onFailure(Throwable caught) {
			  Window.alert("There was an error logging in!\n\n"+caught.getMessage());
			  Cookies.removeCookie("token");
			  Window.Location.assign(Window.Location.getHref().substring(0,Window.Location.getHref().lastIndexOf("/")+1));
	  }
	
	  public void onSuccess(Person u) {
		  if(u != null) {
			  //Window.alert("Logged in Succesfully: " + user);
			  InventoryServiceAsync.impl.getPeople(token, getPeopleCallback);  //dont fetch this unless we login successfully.
			  user = u;
			  userLabel.setText("Welcome, "+user.getName()+".");
		  }
		  else {
			  Window.alert("The token was set, but authentication failed.  Please try logging in again.");
			  InventoryServiceAsync.impl.logout(Cookies.getCookie("token"), logoutCallback);
		  }
	  }
	};
	
	AsyncCallback logoutCallback = new AsyncCallback() {
		  public void onFailure(Throwable caught) {
			  Window.alert("There was an error logging out!\n\n"+caught.getMessage());

	  }
	
	  public void onSuccess(Object arg0) {
		  Cookies.removeCookie("token");
		  Window.alert("Logged out Succesfully.");
		  token = null;
		  //Return user to login page.  UNCOMMENT THIS ON DEPLOYMENT
		  Window.Location.assign(Window.Location.getHref().substring(0,Window.Location.getHref().lastIndexOf("/")+1));
	  }
	};
	
	AsyncCallback<List<Person>> getPeopleCallback = new AsyncCallback<List<Person>>() {
		  public void onFailure(Throwable caught) {
			  Window.alert("There was an error getting the people!\n\n"+caught.getMessage());

	  }
	
	  public void onSuccess(List<Person> l) {
		  //Window.alert("People Retrieved Succesfully");
		  people = l;
		  buildTabs();
		  //buildTree();
		  //contentWrapper.setWidget(new ItemInfoWidget(people.get(0).getDesiredItems().get(0)));
		  //RootPanel.get().add(new ListItemsWidget(l.get(1)));
		  //Window.alert(people.get(0).getName()+" item0name: "+people.get(0).getDesiredItems().get(0).getName()+" item0whoadded: "+ people.get(0).getDesiredItems().get(0).getWhoAddedIt());
	  }
	};
}
